import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  console.log(env, env.VITE_APP_ENV);
  const Timestamp = new Date().getTime();
  return {
    // vite 相关配置
    base: ["development"].includes(mode) ? "/" : "/member",
    server: {
      port: 9000,
      host: true,
      open: true,
      proxy: {
        "/dev-api": {
          target: "http://10.0.3.137:8080",
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ""),
        },
        "/test-api": {
          target: "https://lsapp.szzgh.org:90",
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/test-api/, ""),
        },
        "/uat-api": {
          target: "https://zgfwpre.szzgh.org",
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/uat-api/, "/prod-api"),
        },
        "/prod-api": {
          target: "https://lsapp.szzgh.org:99",
          changeOrigin: true,
        },
      },
    },
    plugins: [
      vue(),
      {
        name: "add-nonce-plugin",
        transformIndexHtml(html) {
          return html.replace(/<script\b/g, '<script nonce="2726c7f26c"');
        },
      },
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    build: {
      sourcemap: true,
      rollupOptions: {
        // input: 'index.html',
        output: {
          experimentalMinChunkSize: 500_000,// 最小分包
          // 静态资源打包做处理
          chunkFileNames: `static/js/[name]-[hash]-${Timestamp}.js`,
          entryFileNames: `static/js/[name]-[hash]-${Timestamp}.js`,
          assetFileNames: `static/[ext]/[name]-[hash]-${Timestamp}.[ext]`,
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
  };
});
